package com.beijing.demo.listnode;

/**
 * 曹旭
 * 2025/4/27
 * 两个链表相加:
 * https://leetcode.cn/problems/add-two-numbers/?envType=problem-list-v2&envId=linked-list
 */
public class ListNodeSum {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null || l2 == null){
            return l1 == null ? l2 : l1;
        }
        int len1 = getLen(l1);
        int len2 = getLen(l2);
        ListNode resultHead = len1 > len2 ? l1 : l2;
        ListNode big = len1 > len2 ? l1 : l2;
        ListNode small = big == l1 ? l2 : l1;
        ListNode pre = resultHead;
        int temp = 0;
        int carry = 0;
        while(small != null){
            temp = big.val + small.val + carry;
            carry = temp >= 10 ? 1 : 0;
            pre.val = temp >= 10 ? temp % 10 : temp;
            big = big.next;
            small = small.next;
            pre = pre.next;
        }
        while(big != null && carry != 0){
            temp = big.val + carry;
            carry = temp >= 10 ? 1 : 0;
            pre.val = temp >= 10 ? temp % 10 : temp;
            pre = pre.next;
            big = big.next;
        }
        if(carry != 0){
            pre.next = new ListNode(1);
        }
        return resultHead;
    }

    public int getLen(ListNode l){
        int len = 0;
        if(l == null){
            return len;
        }
        while(l != null){
            len++;
            l = l.next;
        }
        return len;
    }
}
